// cart.js
const app = getApp()

Page({
  data: {
    cartItems: [],
    totalItems: 0,
    orderNote: '',
    userPoints: 0,
    totalPoints: 0,
    remainingPoints: 0,
    isEditMode: false,
    allSelected: false,
    selectedCount: 0,
    selectedTotalPoints: 0,
    showNoteModal: false,
    tempOrderNote: '',
    showDeleteModal: false,
    deleteItem: null,
    showClearCartModal: false,
    showSuccessToast: false,
    successMessage: '',
    showErrorToast: false,
    errorMessage: '',
    showGlobalLoginModal: false
  },

  onLoad() {
    this.loadCartData()
  },

  onShow() {
    this.loadCartData()
    
    // 监听全局登录弹框状态
    const app = getApp()
    this.setData({
      showGlobalLoginModal: app.globalData.showGlobalLoginModal
    })

    // 设置事件监听
    this.setupEventListeners()
    
    // 初始化TabBar页面（检查并应用等待中的图标配置）
    app.initTabBarPage()
  },

  // 加载选择的服务数据
  loadCartData() {
    const cart = app.globalData.cart
    console.log('加载选择的服务数据:', cart)
    
    // 验证服务数据的完整性
    const validServices = cart.filter(item => {
      const itemId = item._id || item.id
      if (!itemId || !item.name || item.price === undefined || !item.quantity) {
        console.error('服务项目数据不完整:', item)
        console.error('缺少字段:', { 
          id: itemId, 
          name: item.name, 
          price: item.price, 
          quantity: item.quantity 
        })
        return false
      }
      return true
    }).map(item => ({
      ...item,
      selected: true, // 默认选中
      id: item._id || item.id,
      // 确保图片字段存在，如果没有则使用默认图片
      image: item.image || '/images/dishes/hongshao_rou.jpg'
    }))
    
    const totalItems = validServices.reduce((sum, item) => sum + item.quantity, 0)
    const totalPoints = validServices.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    const userPoints = app.globalData.userInfo ? (app.globalData.userInfo.points || 0) : 0
    const remainingPoints = userPoints - totalPoints
    
    // 计算选中状态
    const selectedCount = validServices.filter(item => item.selected).length
    const selectedTotalPoints = validServices
      .filter(item => item.selected)
      .reduce((sum, item) => sum + (item.price * item.quantity), 0)
    
    console.log('有效服务项目:', validServices)
    console.log('服务项目图片信息:', validServices.map(item => ({ name: item.name, image: item.image })))
    console.log('总数量:', totalItems)
    console.log('总积分:', totalPoints)
    console.log('用户积分:', userPoints)
    console.log('剩余积分:', remainingPoints)
    
    this.setData({
      cartItems: validServices,
      totalItems,
      totalPoints,
      userPoints,
      remainingPoints,
      selectedCount,
      selectedTotalPoints,
      allSelected: selectedCount === validServices.length && validServices.length > 0
    })
  },

  // 切换编辑模式
  toggleEditMode() {
    this.setData({
      isEditMode: !this.data.isEditMode
    })
  },

  // 切换全选状态
  toggleSelectAll() {
    const allSelected = !this.data.allSelected
    const cartItems = this.data.cartItems.map(item => ({
      ...item,
      selected: allSelected
    }))
    
    const selectedCount = allSelected ? cartItems.length : 0
    const selectedTotalPoints = allSelected ? 
      cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0) : 0
    
    this.setData({
      cartItems,
      allSelected,
      selectedCount,
      selectedTotalPoints
    })
  },

  // 切换单个商品选择状态
  toggleSelectItem(e) {
    const itemId = e.currentTarget.dataset.id
    const cartItems = this.data.cartItems.map(item => {
      if ((item._id || item.id) === itemId) {
        return { ...item, selected: !item.selected }
      }
      return item
    })
    
    const selectedCount = cartItems.filter(item => item.selected).length
    const selectedTotalPoints = cartItems
      .filter(item => item.selected)
      .reduce((sum, item) => sum + (item.price * item.quantity), 0)
    const allSelected = selectedCount === cartItems.length && cartItems.length > 0
    
    this.setData({
      cartItems,
      selectedCount,
      selectedTotalPoints,
      allSelected
    })
  },

  // 增加数量
  increaseQuantity(e) {
    const itemId = e.currentTarget.dataset.id
    const cart = app.globalData.cart
    const item = cart.find(item => (item._id || item.id) === itemId)
    
    if (item) {
      item.quantity += 1
      app.globalData.cart = cart
      this.loadCartData()
    }
  },

  // 减少数量
  decreaseQuantity(e) {
    const itemId = e.currentTarget.dataset.id
    const cart = app.globalData.cart
    const item = cart.find(item => (item._id || item.id) === itemId)
    
    if (item && item.quantity > 1) {
      item.quantity -= 1
      app.globalData.cart = cart
      this.loadCartData()
    } else if (item && item.quantity === 1) {
      this.removeItem(e)
    }
  },

  // 移除商品
  removeItem(e) {
    const itemId = e.currentTarget.dataset.id
    const item = this.data.cartItems.find(item => (item._id || item.id) === itemId)
    
    if (item) {
      this.setData({
        showDeleteModal: true,
        deleteItem: item
      })
    }
  },



  // 提交预约
  async submitOrder() {
    // 检查用户是否已登录
    if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
      wx.showModal({
        title: '需要登录',
        content: '提交预约功能需要登录后才能使用，是否现在登录？',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            const app = getApp()
            app.showLoginModal()
          }
        }
      })
      return
    }

    if (this.data.selectedCount === 0) {
      this.setData({
        showErrorToast: true,
        errorMessage: '请选择要安排的服务项目'
      })
      
      // 3秒后自动隐藏
      setTimeout(() => {
        this.setData({
          showErrorToast: false
        })
      }, 3000)
      return
    }

    // 显示自定义备注弹窗
    this.setData({
      showNoteModal: true
    })
  },

  // 确认备注并提交预约
  async confirmNoteAndSubmit() {
    const orderNote = this.data.tempOrderNote || ''
    
    // 保存备注信息
    this.setData({
      orderNote: orderNote,
      showNoteModal: false,
      tempOrderNote: ''
    })
    
    // 更新选择的服务中的备注
    if (orderNote) {
      app.globalData.cart.forEach(item => {
        if (!item.note) {
          item.note = orderNote
        }
      })
    }

    // 显示加载提示
    wx.showLoading({
      title: '提交预约中...',
      mask: true
    })
    
    try {
      const order = await app.submitOrder()
      
      if (order) {
        wx.hideLoading()
        // 跳转到安排记录页面
        wx.switchTab({
          url: '/pages/orders/orders'
        })
      } else {
        wx.hideLoading()
      }
    } catch (error) {
      wx.hideLoading()
      console.error('提交预约失败:', error)
      this.setData({
        showErrorToast: true,
        errorMessage: '安排提交失败'
      })
      
      // 3秒后自动隐藏
      setTimeout(() => {
        this.setData({
          showErrorToast: false
        })
      }, 3000)
    }
  },

  // 取消备注弹窗
  cancelNoteModal() {
    this.setData({
      showNoteModal: false,
      tempOrderNote: ''
    })
  },

  // 备注输入
  onNoteInput(e) {
    this.setData({
      tempOrderNote: e.detail.value
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡，防止点击弹窗内容时关闭弹窗
  },

  // 确认删除商品
  confirmDeleteItem() {
    const itemId = this.data.deleteItem._id || this.data.deleteItem.id
    app.removeFromCart(itemId)
    this.loadCartData()
    
    this.setData({
      showDeleteModal: false,
      deleteItem: null
    })
    
    // 显示删除成功提示
    this.setData({
      showSuccessToast: true,
      successMessage: '已删除'
    })
    
    // 3秒后自动隐藏
    setTimeout(() => {
      this.setData({
        showSuccessToast: false
      })
    }, 3000)
  },

  // 取消删除
  cancelDeleteItem() {
    this.setData({
      showDeleteModal: false,
      deleteItem: null
    })
  },

  // 去选择服务
  goToDishes() {
    wx.switchTab({
      url: '/pages/dishes/dishes'
    })
  },

  // 清空选择的服务
  clearCart() {
    this.setData({
      showClearCartModal: true
    })
  },

  // 确认清空选择的服务
  confirmClearCart() {
    app.clearCart()
    this.loadCartData()
    
    this.setData({
      showClearCartModal: false
    })
    
    // 显示清空成功提示
    this.setData({
      showSuccessToast: true,
      successMessage: '已清空'
    })
    
    // 3秒后自动隐藏
    setTimeout(() => {
      this.setData({
        showSuccessToast: false
      })
    }, 3000)
  },

  // 取消清空选择的服务
  cancelClearCart() {
    this.setData({
      showClearCartModal: false
    })
  },

  // 图片加载错误处理
  onImageError(e) {
    const itemId = e.currentTarget.dataset.id
    console.log('图片加载失败，使用默认图片:', itemId)
    
    // 可以在这里设置默认图片或处理图片加载失败的情况
    // 由于我们已经在WXML中设置了默认图片，这里主要是记录日志
  },

  // 关闭全局登录弹框
  onGlobalLoginModalClose() {
    this.setData({
      showGlobalLoginModal: false
    })
    // 同步全局状态
    const app = getApp()
    app.globalData.showGlobalLoginModal = false
  },

  // 全局登录成功回调
  onGlobalLoginSuccess() {
    console.log('全局登录成功，刷新页面数据')
    // 刷新服务选择数据
    this.loadCartData()
  },

  // 设置事件监听
  setupEventListeners() {
    const app = getApp()
    if (app.globalData.eventBus) {
      // 监听全局登录弹框显示事件
      app.globalData.eventBus.on('showGlobalLoginModal', () => {
        this.setData({
          showGlobalLoginModal: true
        })
      })
    }
  },

  // 清理事件监听
  onUnload() {
    const app = getApp()
    if (app.globalData.eventBus) {
      app.globalData.eventBus.off('showGlobalLoginModal')
    }
  }
}) 